package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.MemberElderDto;
import com.zzyl.entity.Elder;
import com.zzyl.entity.MemberElder;
import com.zzyl.exception.BusinessException;
import com.zzyl.mapper.ElderMapper;
import com.zzyl.mapper.MemberElderMapper;
import com.zzyl.service.MemberElderService;
import com.zzyl.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberElderServiceImpl extends ServiceImpl<MemberElderMapper, MemberElder> implements MemberElderService {

    @Autowired
    private ElderMapper elderMapper;
    @Override
    public void saveMember(MemberElderDto memberElderDto) {
        //根据老人id查询老人name
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,memberElderDto.getIdCard())
                .eq(Elder::getName,memberElderDto.getName())
                .between(Elder::getStatus,1,4);//0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder==null){
            throw new BusinessException("老人不存在");
        }
        MemberElder memberElder = BeanUtil.copyProperties(memberElderDto, MemberElder.class);
        memberElder.setMemberId(UserThreadLocal.getUserId());
        memberElder.setElderId(elder.getId());
        try {
            getBaseMapper().insert(memberElder);
        }catch (Exception e){
            throw new BusinessException("绑定失败");
        }
    }

    //分页查询家人列表
    @Override
    public PageResponse<MemberElder> findByPage(Long memberId, Long elderId, Integer pageNum, Integer pageSize) {
        Page<MemberElder> page = new Page<>(pageNum,pageSize);
        page=getBaseMapper().findByPage(page,memberId,elderId);

        return new PageResponse<>(page);
    }
}
